package nio;

import java.nio.ByteBuffer;
import java.util.Optional;

/**
 * NioUtils
 *
 * @author chenxin
 * @date 2022/05/17 17:35
 **/
public class NioUtils {

    /**
     * 功能描述: 读取byteBuffer内容到堆内存中
     *
     * @param buffer
     * @author: chenxin
     * @date: 2022/5/23
     */
    public static String getString(ByteBuffer buffer) {
        StringBuilder result = new StringBuilder();
        while (buffer.hasRemaining()) {
            byte b = buffer.get();
            result.append((char) b);
        }
        return result.toString();
    }

    public static String getString(ByteBuffer buffer, int count) {
        StringBuilder result = new StringBuilder();
        int index = 0;
        while (buffer.hasRemaining() && index < count) {
            index++;
            byte b = buffer.get();
            result.append((char) b);
        }
        return result.toString();
    }

    // 不改变position位置读取
    public static String getStringNotMove(ByteBuffer buffer) {
        return getStringNotMove(buffer,null);
    }

    // 不改变position位置读取
    public static String getStringNotMove(ByteBuffer buffer, Integer count) {
        int limit = buffer.limit();
        count = Optional.ofNullable(count).orElse(limit);

        StringBuilder result = new StringBuilder();
        for (int i = 0; i < limit && i < count; i++) {
            result.append((char) buffer.get(i));
        }
        return result.toString();
    }


}